package com.cloud.tools.log.config.aspect;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.cloud.common.core.cons.APICons;
import com.cloud.common.core.utils.IpUtils;
import com.cloud.common.log.annotation.Log;
import com.cloud.common.log.enums.BusinessStatus;
import com.cloud.tools.log.project.model.entity.OperateLog;
import com.cloud.tools.log.project.service.IOperateLogService;
import com.google.common.base.Throwables;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.*;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpMethod;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;
import java.net.URLDecoder;
import java.util.Collection;
import java.util.Iterator;
import java.util.Map;
import java.util.Objects;

/**
 * 统一切点日志处理
 *
 * @author yan
 */
@Slf4j
@Aspect
@Component
public class LogAspect {
    @Autowired
    private IOperateLogService operateLogService;

    @Pointcut("@annotation(com.cloud.common.log.annotation.Log)")
    @SuppressWarnings("EmptyMethod")
    public void pointCut() {
    }

    @Before(value = "pointCut()")
    public void doBefore(JoinPoint joinPoint) {
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = requestAttributes.getRequest();
        if (Objects.isNull(request.getAttribute(APICons.API_BEGIN_TIME))) {
            request.setAttribute(APICons.API_BEGIN_TIME, System.currentTimeMillis());
        }
    }

    /**
     * 处理完请求后执行
     *
     * @param joinPoint  切点
     * @param jsonResult 响应数据
     */
    @AfterReturning(pointcut = "pointCut()", returning = "jsonResult")
    public void doAfterReturning(JoinPoint joinPoint, Object jsonResult) {
        handleLog(joinPoint, null, jsonResult);
    }

    /**
     * 拦截异常操作
     *
     * @param joinPoint 切点
     * @param e         异常
     */
    @AfterThrowing(value = "pointCut()", throwing = "e")
    public void doAfterThrowing(JoinPoint joinPoint, Exception e) {
        handleLog(joinPoint, e, null);
    }

    /**
     * 处理日志
     *
     * @param joinPoint  切点
     * @param e          异常
     * @param jsonResult 返回数据
     */
    protected void handleLog(final JoinPoint joinPoint, final Exception e, Object jsonResult) {
        try {
            ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
            HttpServletRequest request = requestAttributes.getRequest();
            // 获得注解
            Log controllerLog = getAnnotationLog(joinPoint);
            if (controllerLog == null) {
                return;
            }

            // *========数据库日志=========*//
            OperateLog operLog = new OperateLog();
            //默认成功状态码
            operLog.setStatus(BusinessStatus.SUCCESS.ordinal());
            //请求的地址
            String ip = IpUtils.getIpAddr(request);
            operLog.setOperIp(ip);
            //返回参数 JSON.toJSONString 空会打印 "null"  此处替换成 ""  SerializerFeature.WriteMapNullValue 防止$引用
            operLog.setJsonResult(StringUtils.replace(JSON.toJSONString(jsonResult, SerializerFeature.WriteMapNullValue), "null", ""));
            //请求路径 /open/test/1
            operLog.setOperUrl(request.getRequestURI());
            //操作人
            String username = request.getHeader(APICons.API_OPER_NAME);
            if (StringUtils.isNotBlank(username)) {
                operLog.setOperName(username);
            }

            //处理异常
            if (e != null) {
                operLog.setStatus(BusinessStatus.FAIL.ordinal());
                operLog.setErrorMsg(StringUtils.substring(Throwables.getStackTraceAsString(e), 0, 2000));
            }
            //设置方法名称
            String className = joinPoint.getTarget().getClass().getName();
            String methodName = joinPoint.getSignature().getName();
            operLog.setMethod(className + "." + methodName + "()");
            //设置请求方式
            operLog.setRequestMethod(request.getMethod());
            //param参数 中文转码
            operLog.setOperParam(URLDecoder.decode(StringUtils.isNotBlank(request.getQueryString()) ? request.getQueryString() : ""));
            //处理设置注解上的参数
            getControllerMethodDescription(joinPoint, controllerLog, operLog);
            //执行时间
            operLog.setRunTime(request.getAttribute(APICons.API_BEGIN_TIME) != null ? (System.currentTimeMillis() - (Long) request.getAttribute(APICons.API_BEGIN_TIME)) : 0);
            //保存数据库
            operateLogService.saveAsyncLog(operLog);
        } catch (Exception ex) {
            // 记录本地异常日志
            log.error("==AOP通知异常==", ex);
        }
    }

    /**
     * 是否存在注解，如果存在就获取
     */
    private Log getAnnotationLog(JoinPoint joinPoint) {
        Signature signature = joinPoint.getSignature();
        MethodSignature methodSignature = (MethodSignature) signature;
        Method method = methodSignature.getMethod();
        if (method != null) {
            return method.getAnnotation(Log.class);
        }
        return null;
    }

    /**
     * 获取注解中对方法的描述信息 用于Controller层注解
     *
     * @param log        日志
     * @param operateLog 操作日志
     * @throws Exception
     */
    public void getControllerMethodDescription(JoinPoint joinPoint, Log log, OperateLog operateLog) {
        // 设置action动作
        operateLog.setBusinessType(log.businessType().ordinal());
        // 设置标题
        operateLog.setTitle(log.title());
        // 设置操作人类别
        operateLog.setOperType(log.operatorType().ordinal());
        // 是否需要保存request，参数和值
        if (log.isSaveRequestData()) {
            // 获取参数的信息，传入到数据库中。
            setRequestValue(joinPoint, operateLog);
        }
    }

    /**
     * 获取请求的body参数，放到log中
     *
     * @param operateLog 操作日志
     * @throws Exception 异常
     */
    private void setRequestValue(JoinPoint joinPoint, OperateLog operateLog) {
        String requestMethod = operateLog.getRequestMethod();
        if (HttpMethod.PUT.name().equals(requestMethod) || HttpMethod.POST.name().equals(requestMethod)) {
            String body = argsArrayToString(joinPoint.getArgs());
            operateLog.setOperBody(body);
        }
    }

    /**
     * 参数拼装
     */
    private String argsArrayToString(Object[] paramsArray) {
        String params = "";
        if (paramsArray != null && paramsArray.length > 0) {
            for (int i = 0; i < paramsArray.length; i++) {
                if (!isFilterObject(paramsArray[i])) {
                    try {
                        Object jsonObj = JSON.toJSON(paramsArray[i]);
                        params += jsonObj.toString() + " ";
                    } catch (Exception e) {
                    }
                }
            }
        }
        return params.trim();
    }

    /**
     * 判断是否需要过滤的对象。
     *
     * @param o 对象信息。
     * @return 如果是需要过滤的对象，则返回true；否则返回false。
     */
    @SuppressWarnings("rawtypes")
    public boolean isFilterObject(final Object o) {
        Class<?> clazz = o.getClass();
        if (clazz.isArray()) {
            return clazz.getComponentType().isAssignableFrom(MultipartFile.class);
        } else if (Collection.class.isAssignableFrom(clazz)) {
            Collection collection = (Collection) o;
            for (Iterator iter = collection.iterator(); iter.hasNext(); ) {
                return iter.next() instanceof MultipartFile;
            }
        } else if (Map.class.isAssignableFrom(clazz)) {
            Map map = (Map) o;
            for (Iterator iter = map.entrySet().iterator(); iter.hasNext(); ) {
                Map.Entry entry = (Map.Entry) iter.next();
                return entry.getValue() instanceof MultipartFile;
            }
        }
        return o instanceof MultipartFile || o instanceof HttpServletRequest || o instanceof HttpServletResponse;
    }

}
